package com.letoken.platform.repo.web3.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.letoken.platform.pub.enums.LetokenApiResponseEnum;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.pub.res.token.TokenErc20TxRes;
import com.letoken.platform.pub.res.token.TokenTxRes;
import com.letoken.platform.pub.res.token.okc.OKCTransaction;
import com.letoken.platform.pub.util.HttpClientUtil;
import com.letoken.platform.repo.wallet.po.Web3ChainProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.*;

/**
 * @author letokenlabs
 * @date 2022/11/16$
 */
@Slf4j
@Component
public class OkcScanUtil extends EvmUtil {

    public static List<TokenErc20TxRes> getTokenErc20Txs(Web3ChainProvider provider, String contractAddress, String walletAddress, Integer page, Integer pageSize, String sort) {
        Map<String, String> parame = new HashMap<>();
        parame.put("chainShortName", provider.getNetwork());
        parame.put("address", walletAddress);
        parame.put("page", page.toString());
        parame.put("limit", pageSize.toString());
        Map<String, String> header = new HashMap<>();
        header.put("Ok-Access-Key", provider.getApiKey());
        String res;

        try {
            String url = String.format("%s/api/v5/explorer/address/transaction-list", provider.getApiUrl());
            res = HttpClientUtil.sendGet(url, parame, header, null);
        } catch (Exception e) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_WALLET_TX_001);
        }

        JSONObject jsonObject = JSON.parseObject(res);
        List<TokenErc20TxRes> list = new ArrayList<>();
        if ("0".equals(jsonObject.getString("code"))) {

            jsonObject = jsonObject.getJSONObject("data");
            JSONObject transactionLists = jsonObject.getJSONObject("transactionLists");

            List<OKCTransaction> transactions = JSON.parseArray(transactionLists.toJSONString(), OKCTransaction.class);
            transactions.forEach(it->{
                TokenErc20TxRes item = new TokenErc20TxRes();
                item.setHash(it.getTxId());
                item.setBlockHash(it.getBlockHash());
                item.setBlockNumber(it.getHeight());
                item.setFrom(it.getFrom());
                item.setTo(it.getTo());
                item.setValue(it.getAmount());
                item.setContractAddress(it.getTokenContractAddress());
                item.setGasUsed(it.getTxFee());
                item.setTimeStamp(it.getTransactionTime());
                item.setTokenName(it.getTokenId());
                item.setTokenSymbol(it.getTransactionSymbol());
                list.add(item);
            });

        } else {
            throw new ApiServiceException(jsonObject.getString("msg"));
        }
        return list;
    }

    public static List<TokenTxRes> getTokenTxs(Web3ChainProvider provider, String walletAddress, Integer page, Integer pageSize, String sort) {
        Map<String, String> parame = new HashMap<>();
        parame.put("chainShortName", provider.getNetwork());
        parame.put("address", walletAddress);
        parame.put("page", page.toString());
        parame.put("limit", pageSize.toString());
        Map<String, String> header = new HashMap<>();
        header.put("Ok-Access-Key", provider.getApiKey());
        String res;

        try {
            String url = String.format("%s/api/v5/explorer/address/transaction-list", provider.getApiUrl());
            res = HttpClientUtil.sendGet(url, parame, header, null);
        } catch (Exception e) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_WALLET_TX_001);
        }
        JSONObject jsonObject = JSON.parseObject(res);
        List<TokenTxRes> list = new ArrayList<>();
        if ("0".equals(jsonObject.getString("code")) && !jsonObject.getJSONArray("data").isEmpty()) {

            JSONArray transactionLists = jsonObject.getJSONArray("data").getJSONObject(0).getJSONArray("transactionLists");
            List<OKCTransaction> transactions = JSON.parseArray(transactionLists.toJSONString(), OKCTransaction.class);
            transactions.forEach(it->{
                TokenTxRes item = new TokenTxRes();
                item.setHash(it.getTxId());
                item.setBlockHash(it.getBlockHash());
                item.setBlockNumber(it.getHeight());
                item.setFrom(it.getFrom());
                item.setValue(it.getAmount());
                item.setTo(it.getTo());
                item.setGasUsed(it.getTxFee());
                item.setTimeStamp(it.getTransactionTime());
                item.setTxreceipt_status(it.getState());
                list.add(item);
            });

        } else {
            throw new ApiServiceException(jsonObject.getString("msg"));
        }
        return list;
    }
}
